﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BB.Apostas.Filters;
using BB.Apostas.Models;
using WebMatrix.WebData;
using Newtonsoft.Json;

namespace BB.Apostas.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class ClassificacaoController : Controller
    {
        private ApostasBalasDbContext db = new ApostasBalasDbContext();

        public ActionResult Index()
        {
            var competicaoactiva = db.Registos
               .Where(cr => cr.UserId == WebSecurity.CurrentUserId && cr.Active == true).SingleOrDefault();

            if (competicaoactiva == null)
                return View();

            var ultimajornada = db.Jornadas
                .Where(j => j.Fulfilled == true && j.CompeticaoId == competicaoactiva.CompeticaoId)
                .OrderByDescending(j => j.Id)
                .FirstOrDefault();

            ViewBag.Active = competicaoactiva.Competicao.Name;
            ViewBag.Jornadas = new SelectList(db.Jornadas
                .Where(j => j.Fulfilled == true && j.CompeticaoId == competicaoactiva.CompeticaoId)
                .OrderByDescending(j => j.Id)
                .ToList(), "Id", "Name", ultimajornada == null ? 0 : ultimajornada.Id);

            var classificacao = new List<Classificacao>();

            if (ultimajornada != null)
                classificacao = db.Classicacoes
                    .Where(c => c.JornadaId == ultimajornada.Id && c.CompeticaoId == competicaoactiva.CompeticaoId)
                    .OrderByDescending(c => c.Score)
                    .ToList();

            return View(classificacao);
        }      

        public JsonResult GetRank(int idjornada = 0)
        {
            var competicaoactiva = db.Registos
            .Where(cr => cr.UserId == WebSecurity.CurrentUserId && cr.Active == true).Single();
            var classificacao = db.Classicacoes
                    .Where(c => c.JornadaId == idjornada && c.CompeticaoId == competicaoactiva.CompeticaoId)
                    .OrderByDescending(c => c.Score)
                    .ToList();
            return Json(classificacao, JsonRequestBehavior.AllowGet);
        }

    }
}
